import axios from 'axios'
import qs, { stringify } from 'qs'
const instance = axios.create({
    //baseURL: 'http://47.104.8.66:8080',
     //baseURL: 'http://localhost:8080',
    // baseURL: 'http://47.104.8.66:8080',
    // baseURL: 'http://localhost:8080',
    // baseURL: 'http://192.168.100.199:8080',
    headers: { 'content-Type': 'application/json;charset=UTF-8' },
    // headers: { 'content-Type': 'application/x-www-form-urlencoded' }
    // baseURL: 'http://localhost:8080'
    // baseURL: 'http://www.hbzhiku.org.cn/api'
    baseURL: process.env.API_ROOT,
    timeout: 2500,
})
//http request 请求拦截器,有token则配置token
// instance.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

instance.interceptors.request.use(
    config => {
        return config
    },
    err => Promise.reject(err)
)
// http response 拦截器
instance.interceptors.response.use(
    res => res,
    err => Promise.reject(err)
)
// export default instance
export function get(url, params) {
    return new Promise((resolve, reject) => {
        var Url = ''
        if (params === null || params === undefined) {
            Url = url
        } else {
            Url = url + '?' + qs.stringify(params)
        }
        instance.get(Url)
            .then(res => { resolve(res.data) },
                err => { reject(err) })
    })
}
export function post(url, params) {
    // console.log('参数', JSON.stringify(params))
    // console.log('参数', qs.stringify(params))
    let Url
    let trans_params
    let arr = []
    for (let item in params) {
        if (params[item] instanceof Object) {
            trans_params = params[item]
        } else {
            arr.push(encodeURIComponent(item) + '=' + encodeURIComponent(params[item]))
            console.log('arr', arr)
        }
    }
    let en = arr.length > 0 ? "?" + arr.join("&") : ''
    Url = url + en
    console.log('Url', Url, trans_params)
    return new Promise((resolve, reject) => {
        instance.post(Url, trans_params)
            .then(res => { resolve(res.data) },
                err => { reject(err) })
    })
}
export function put(url, params) {
    return new Promise((resolve, reject) => {
        instance.put(url, params)
            .then(res => { resolve(res.data) },
                err => { reject(err) })
    })
}
export function del(url, params) {
    return new Promise((resolve, reject) => {
        let Url = url + '?' + qs.stringify(params)
        instance.post(Url)
            .then(res => { resolve(res.data) },
                err => { reject(err) })
    })
}
